package com.itmuch.usercenter.auth;

import com.itmuch.usercenter.security.SecurityException;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author caiqian
 * @date 2021/5/11 11:20
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionErrorHandler {

  @ExceptionHandler(SecurityException.class)
  public ResponseEntity<ErrorBody> error(SecurityException e) {
    log.warn("验证token时,发生了异常", e);

    return new ResponseEntity(
        ErrorBody.builder()
            .body("token非法,用户不允许访问!")
            .status(HttpStatus.UNAUTHORIZED.value())
            .build(),
        HttpStatus.UNAUTHORIZED
    );
  }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
class ErrorBody {

  private String body;
  private int status;
}
